// pages/person/selectAddress/index.js
const $api = require('../../../../request/api').API;
import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import { getAddress, initLocationPersmiss } from '../../../../utils/util';
const app = getApp();
// var qqmapsdk;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    variantIds: '', //是否是从提交订单页面新增地址来的
    relationBeeperId: '',
    relationBeeperType: '',
    // 中心经纬度
    latitude: 0,
    longitude: 0,
    id: '',
    // 目标记录点
    markers: [],
    address: '', // 地址
    detailAddress: '', // 这个是用来地址解析的
    province: '', //省
    city: '', //市
    district: '', //区
    street: '', //街道
    houseNumber: '', //门牌号
    phone: '', //电话
    linkName: '', //联系人
    // defaultStart:0,//是否开启默认地址，0表示不启用，1表示启用
    radio: '1',
    isEdit: false, // 是否是编辑，实际上就是有没有地址显示
    icon: {
      normal: '../../../static/no-selected.png',
      active: '../../../static/selected.png'
    },
    tag: '',
    prop: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    const { id, variantIds, relationBeeperId, relationBeeperType } = options;
    if (id) {
      this.setData({
        id
      });
      this.getHarvestAddress();
    } else {
      this.initLocationPersmiss();
    }

    if (variantIds) {
      // 有variantIds表示是从提交订单页面来新增的，那么保存的时候就要判断是不是距离超出配送范围
      this.setData({
        variantIds
      });
    }
    if (relationBeeperId) {
      this.setData({
        relationBeeperId,
        relationBeeperType
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},
  // 防止页面滚动，map组件里面放其它组件偶bug
  touchmove() {
    return;
  },
  // 点击聚焦
  clickFocus(e) {
    let prop = e.currentTarget.dataset.prop;
    this.setData({
      prop
    });
  },
  // 输入
  inputValue(e) {
    let prop = e.currentTarget.dataset.prop;
    let value = e.detail.value;
    this.setData({
      [prop]: value
    });
  },
  // 获取收货地址详情
  getHarvestAddress() {
    $api.getHarvestAddress({ id: this.data.id }).then(res => {
      let data = res.data.data;
      this.data.markers[0] = {
        latitude: data.latitude,
        longitude: data.longitude,
        iconPath: '../../../../static/position.png',
        width: 35,
        height: 35
      };
      this.setData({
        address: data.address,
        province: data.provinceName,
        city: data.cityName,
        district: data.areaName,
        street: data.street,
        houseNumber: data.houseNumber,
        latitude: data.latitude - 0.0052,
        longitude: data.longitude,
        linkName: data.linkName,
        phone: data.phone,
        // defaultStart:data.defaultStart,
        isEdit: true,
        markers: this.data.markers
      });
    });
  },
  // 选择地址
  selectAddress() {
    // 根据地址信息为中心选择地址
    if (this.data.address) {
      wx.chooseLocation({
        latitude: this.data.markers[0].latitude,
        longitude: this.data.markers[0].longitude,
        success: res => {
          this.data.markers[0].latitude = res.latitude;
          this.data.markers[0].longitude = res.longitude;
          this.setData({
            detailAddress: res.address + res.name,
            address: res.name,
            latitude: res.latitude - 0.0052,
            longitude: res.longitude,
            markers: this.data.markers
          });
          this.getAddress();
        },
        fail: err => {
          console.log(err);
        }
      });
    } else {
      // 根据当前定位为中心选择地址
      wx.chooseLocation({
        success: res => {
          this.data.markers[0].latitude = res.latitude;
          this.data.markers[0].longitude = res.longitude;
          this.setData({
            detailAddress: res.address + res.name,
            address: res.name,
            latitude: res.latitude - 0.0052,
            longitude: res.longitude,
            markers: this.data.markers
          });
          this.getAddress();
        },
        fail: err => {
          console.log(err);
        }
      });
    }
  },
  // 选择性别
  sexChange(e) {
    this.setData({
      radio: e.detail
    });
  },
  // 选择添加标签
  addTag(e) {
    if (e.currentTarget.dataset.tag == this.data.tag) {
      this.setData({
        tag: 0
      });
      return;
    }
    this.setData({
      tag: e.currentTarget.dataset.tag
    });
  },
  initLocationPersmiss() {
    initLocationPersmiss().then(res => {
      this.data.markers[0] = {
        latitude: res.location.lat,
        longitude: res.location.lng,
        iconPath: '../../../../static/position.png',
        width: 35,
        height: 35
      };
      this.setData({
        latitude: res.location.lat - 0.0052,
        longitude: res.location.lng,
        markers: this.data.markers
      });
    });
  },
  // 通过地址获取经纬度,地址解析(实际上就是为了进一步精确地址，因为chooseLocation获取的经纬度不准确)
  // getLatLng(){
  //     getLatLng(this.data.detailAddress).then(res=>{
  //         let latitude =  res.location.lat
  //         let longitude = res.location.lng

  //         // 地址解析可能会解析错误，这个时候后解析的误差如果和chooseLocation返回的经纬度误差过大那么还是用chooseLocation返回的经纬度
  //         if(Math.abs(this.data.latitude-res.lat)>0.01||Math.abs(this.data.longitude-res.lng)>0.01){
  //             latitude =  this.data.latitude
  //             longitude = this.data.longitude
  //         }
  //         this.data.markers[0].longitude = longitude
  //         this.data.markers[0].latitude = latitude
  //         this.setData({
  //             latitude:latitude-0.0052,
  //             longitude:longitude,
  //             markers:this.data.markers
  //         })
  //         this.getAddress()
  //     })
  // },
  // 通过经纬度获取地址,逆地址解析
  getAddress() {
    getAddress(this.data.markers[0].latitude, this.data.markers[0].longitude).then(res => {
      let province = res.address_component.province || '';
      let city = res.address_component.city || '';
      let district = res.address_component.district || '';
      let street = res.address_component.street || '';
      this.setData({
        province,
        city,
        district,
        street
      });
    });
  },
  // 检查输入是否正确
  checkSaveAddress() {
    const regex = /^\d{1,12}$/;
    if (!this.data.address) {
      Toast('请选择收货地址');
      return false;
    }
    if (!this.data.houseNumber) {
      Toast('请填写门牌号');
      return false;
    }
    if (!this.data.linkName) {
      Toast('请填写收货人姓名');
      return false;
    }
    if (!this.data.phone) {
      Toast('请填写联系电话');
      return false;
    }
    if (!regex.test(this.data.phone)) {
      Toast('联系电话格式不正确');
      return false;
    }
    return true;
  },
  // 保存地址
  saveAddress() {
    if (!this.checkSaveAddress()) return;
    let params = {
      latitude: this.data.markers[0].latitude,
      longitude: this.data.markers[0].longitude,
      phone: this.data.phone,
      linkName: this.data.linkName,
      address: this.data.address,
      provinceName: this.data.province,
      cityName: this.data.city,
      areaName: this.data.district,
      streetName: this.data.street,
      houseNumber: this.data.houseNumber
    };
    if (this.data.variantIds) {
      params.variantIds = this.data.variantIds;
      params.keepUp = 0;
    }
    if (this.data.relationBeeperId) {
      params.relationBeeperId = this.data.relationBeeperId;
      params.relationBeeperType = this.data.relationBeeperType;
    }
    if (!this.data.id) {
      // 新增
      this.addAddress(params);
    } else {
      // 编辑
      this.editAddress(params);
    }
  },
  // 添加地址
  addAddress(params) {
    $api.saveAddress(params).then(res => {
      let data = res.data.data;
      if (data === 0) {
        Dialog.confirm({
          title: '提示',
          message: '您的地址超出商家配送范围了哦',
          cancelButtonText: '调整地址',
          confirmButtonText: '仍然保存'
        }).then(res => {
          params.keepUp = 1;
          $api.saveAddress(params).then(res => {
            app.globalData.exceed = true;
            app.globalData.harvestAddressId = res.data.data;
            wx.showToast({
              title: '保存成功',
              success: res => {
                wx.navigateBack({
                  delta: 1
                });
              }
            });
          });
        });
      } else {
        wx.showToast({
          title: '保存成功',
          success: res => {
            if (params.variantIds) {
              // 从提交订单页面来的那么就需要返回数据回去
              app.globalData.harvestAddressId = data;
              app.globalData.linkName = this.data.linkName;
              app.globalData.phone = this.data.phone;
              app.globalData.address = this.data.address;
              app.globalData.houseNumber = this.data.houseNumber;
            }
            wx.navigateBack({
              delta: 1
            });
          }
        });
      }
    });
  },
  // 编辑地址
  editAddress(params) {
    params.harvestAddressId = this.data.id;
    $api.updateAddressInfo(params).then(res => {
      let data = res.data.data;
      if (data === 0) {
        Dialog.confirm({
          title: '提示',
          message: '您的地址超出商家配送范围了哦',
          cancelButtonText: '调整地址',
          confirmButtonText: '仍然保存'
        }).then(res => {
          params.keepUp = 1;
          $api.updateAddressInfo(params).then(res => {
            app.globalData.exceed = true;
            app.globalData.harvestAddressId = res.data.data;
            wx.showToast({
              title: '保存成功',
              success: res => {
                wx.navigateBack({
                  delta: 1
                });
              }
            });
          });
        });
      } else {
        wx.showToast({
          title: '保存成功',
          success: res => {
            if (params.variantIds) {
              // 从提交订单页面来的那么就需要返回数据回去
              app.globalData.harvestAddressId = this.data.id;
              app.globalData.linkName = this.data.linkName;
              app.globalData.phone = this.data.phone;
              app.globalData.address = this.data.address;
              app.globalData.houseNumber = this.data.houseNumber;
            }
            wx.navigateBack({
              delta: 1
            });
          }
        });
      }
    });
  },
  // 删除地址
  deleteAddress() {
    Dialog.confirm({
      title: '提示',
      message: '地址删除后无法恢复是否删除地址？',
      cancelButtonText: '取消',
      confirmButtonText: '删除'
    }).then(res => {
      $api.deleteAddressInfo({ id: this.data.id, state: -1 }).then(res => {
        Toast.success({
          message: '删除成功',
          forbidClick: true,
          duration: 1000
        });
        setTimeout(() => {
          if (this.data.variantIds) {
            app.globalData.delete = true;
            app.globalData.harvestAddressId = this.data.id;
          }
          wx.navigateBack({
            delta: -1
          });
        }, 1000);
      });
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {}
});
